<template>
  <div>
    <section class="classify">
      <div class="item">
        <span class="star">所属分类</span>
        <span class="middle-text">{{catname}}</span>
      </div>
    </section>
    <section class=" enterprise">
      <h6>企业资质</h6>
      <AddBransItem leftText="企业名称" :showWarn="!brandForm.company && showWarn" :rightText="checkNameText">
        <input type="text" placeholder="请输入企业名称" maxlength="30" slot="middledom" @blur="onBlur('name')" v-model="brandForm.company" v-inputDelete>
      </AddBransItem>
      <AddBransItem leftText="企业地址" :showWarn="!brandForm.address && showWarn" :rightText="checkAddress">
        <input type="text" placeholder="请输入企业地址" maxlength="140" slot="middledom" @blur="onBlur('address')" @input="inputAddress" v-model.trim="brandForm.address" v-inputDelete>
      </AddBransItem>
      <AddBransItem leftText="企业网站" :showWarn="!brandForm.homepage && showWarn" :rightText="checkUrl">
        <input type="text" placeholder="请输入企业网站" maxlength="30" slot="middledom" @blur="onBlur('url')" v-model="brandForm.homepage">
      </AddBransItem>
      <AddBransItem leftText="营业执照" :showWarn="!brandForm.homepage && showWarn" :rightText="checkImgUrl">
      </AddBransItem>
      <UploadItem tipText="对焦营业执照使图文清晰可见" :width="6.9" :hight="3" :imgUrl="brandForm.license" @fileUrl="onLicense"></UploadItem>
      <div class="format-box">
        <div>
          <p>（上传为JPG、PNG、GIF格式，大小在5M以内）</p>
        </div>
        <div class="see" @click="showTemplate('yyzz')">
          <span class="see-icon"></span>
          <span>模板</span>
        </div>
      </div>
    </section>
    <section class="phone-box">
      <AddBransItem leftText="手机号" :showWarn="!brandForm.tel && showWarn" :rightText="checkPhone">
        <input type="tel" slot="middledom" v-model="oldTel" readonly v-if="oldTel">
        <input type="tel" placeholder="请输入手机号" @input="inputPhone" maxlength="11" slot="middledom" @blur="onBlur('phone')" v-model="brandForm.tel" v-inputBlur v-else>
      </AddBransItem>
      <AddBransItem leftText="验证码" :height="0.9" :showWarn="!imgcode && showWarn" v-show="codeShow">
        <input type="text" maxlength="8" placeholder="请输入验证码" slot="middledom" v-model="imgcode" v-inputBlur @blur="onBlur('imgcode')">
        <div class="img-code-box" slot="rightdom">
          <img :src="imgCodeUrl" @click="getRandom(10)">
        </div>
      </AddBransItem>
      <div class="tap-text" v-show="codeShow">
        <span @click="getRandom(10)">看不清，换一张</span>
      </div>
    </section>
    <section class="code-box">
      <AddBransItem leftText="短信验证码" :showWarn="!brandForm.verify && showWarn" :rightText="checkCode" :rightDom="checkCode">
        <input type="tel" placeholder="请输入短信验证码" maxlength="6" slot="middledom" @blur="onBlur('verify')" v-model="brandForm.verify" v-inputBlur>
        <span slot="rightdom" class="right-text" @click="checkImageCode">{{codeText}}</span>
      </AddBransItem>
    </section>
  </div>
</template>
<script>
import AddBransItem from './AddBransItem'
import UploadItem from '../../../components/UploadItem'
import { mapState } from 'vuex'
import consts from '../../../common/consts'
import { isvalidWebsite, isvalidPhone } from '../../../common/validate'
import { addressRule, numRule } from '../../../common/inputRule'

export default {
  components: {
    AddBransItem,
    UploadItem
  },
  props: {
    showWarn: {
      type: Boolean,
      default: false
    },
    uesrOldInfo: {
      type: Object
    }
  },
  data() {
    return {
      imgCodeUrl: '', // 图片验证码地址
      random: null, // 随机数
      codeTimer: null,
      countDown: -1,
      brandForm: {
        classify: null, // 行业名
        catid: null, // 行业id
        company: null, // 企业名
        address: null, // 企业地址
        homepage: null, // 企业网址
        license: null, // 企业执照
        tel: null, // 手机号
        verify: null, // 短信验证码
      },
      imgcode: null, //  图片验证码
      checkNameText: '', // 校验提示
      checkAddress: '', // 校验提示
      checkUrl: '', // 校验提示
      checkImgUrl: '', // 校验提示
      checkPhone: '', // 校验提示
      checkCode: '', // 校验提示
      rightText: '',
      codeShow: false, // 默认图片验证码不显示
      checkPhoneFlag: false, // 校验手机号是否通过
      oldTel: ''
    }
  },
  watch: {
    uesrOldInfo(newVal) {
      if (newVal) {
        // 企业名称
        this.brandForm.company = newVal.gongsi
        // 企业地址
        this.brandForm.address = newVal.dizhi
        // 企业网站
        this.brandForm.homepage = newVal.homepage
        // 营业执照
        this.brandForm.license = newVal.license
        // 手机号
        this.brandForm.tel = newVal.tel
        this.oldTel = newVal.tel.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
        this.checkPhoneFlag = true
      }
    }
  },
  computed: {
    ...mapState({
      catname: s => s.catName
    }),
    codeText() {
      if (this.countDown === -1) {
        return '获取验证码'
      }
      if (this.countDown === 0) {
        return '重新获取验证码'
      } else {
        return '(' + this.countDown + ')秒后重新获取'
      }
    }
  },
  mounted() {
    if (window.sessionStorage.getItem('brandFrom')) {
      let formData = JSON.parse(window.sessionStorage.getItem('brandFrom'))
      this.brandForm.company = formData.company
      this.brandForm.address = formData.address
      this.brandForm.homepage = formData.homepage
      this.brandForm.tel = formData.tel
    }
    // 获取图片随机数
    // this.getRandom(10)
  },
  methods: {
    next() {
      if (!this.brandForm.company) {
        this.checkNameText = '必填项'
        this.$emit('onErrShow', true)
        return
      }
      if (!this.brandForm.address) {
        this.checkAddress = '必填项'
        this.$emit('onErrShow', true)
        return
      }
      if (!this.brandForm.homepage) {
        this.checkUrl = '必填项'
        this.$emit('onErrShow', true)
        return
      }
      if (!this.brandForm.license) {
        this.checkImgUrl = '必填项'
        this.$emit('onErrShow', true)
        return
      }
      if (!this.brandForm.tel) {
        this.checkPhone = '必填项'
        this.$emit('onErrShow', true)
        return
      }
      if (!this.brandForm.verify) {
        this.checkCode = '必填项'
        this.$emit('onErrShow', true)
        return
      }
      this.$api.getVerifSms(this.$route.query.catid, {
        tel: this.brandForm.tel,
        verify: this.brandForm.verify,
        auType: 1
      }).then(data => {
        if (data.data.status == 1) {
          window.scrollTo(0, 0)
          this.$emit('onStep', 2)
          this.step = 2
          this.brandForm.classify = this.catname
          this.brandForm.catid = this.$route.query.catid
          window.sessionStorage.setItem('brandFrom', JSON.stringify(this.brandForm))
        } else {
          this.checkCode = data.data.msg
          this.$emit('onErrShow', true)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    onLicense(e) {
      this.brandForm.license = e
    },
    // 校验
    onBlur(e) {
      if (e === 'name') {
        if (!this.brandForm.company) {
          this.checkNameText = '必填项'
          return
        } else {
          if (this.brandForm.company.length > 30) {
            this.checkNameText = '最多30个字'
            return
          }
          // 校验企业名
          this.validateCompanyName(this.brandForm.company)
          return
        }
      }
      if (e === 'address') {
        if (!this.brandForm.address) {
          this.checkAddress = '必填项'
          return
        } else {
          this.checkAddress = ''
          return
        }
      }
      if (e === 'url') {
        if (!this.brandForm.homepage) {
          this.checkUrl = '必填项'
          return
        }
        if (!isvalidWebsite(this.brandForm.homepage)) {
          this.checkUrl = '网址有误'
          return
        } else {
          this.checkUrl = ''
        }
      }
      if (e === 'phone') {
        if (!this.brandForm.tel) {
          this.checkPhone = '必填项'
          return
        }
        if (!isvalidPhone(this.brandForm.tel)) {
          this.checkPhone = '手机号有误'
        } else {
          this.checkPhone = ''
        }
      }
      if (e === 'verify') {
        if (!this.brandForm.verify) {
          this.checkCode = '必填项'
          return
        }
        if (this.brandForm.verify.length != 6) {
          this.checkCode = '长度为6位'
        } else {
          this.checkCode = ''
        }
      }
      if (e === 'imgcode') {
        if (this.imgcode) {
          // 去掉空格 大于4时候取前四位
          this.imgcode = this.imgcode.replace(/\s+/g, '')
          if (this.imgcode.length > 4) {
            this.imgcode = this.imgcode.substr(0, 4)
          }
        }
      }
    },
    // 校验公司名称
    validateCompanyName(companyName) {
      this.$api.validateCompanyName(this.$route.query.catid, {
        company: companyName
      }).then(data => {
        if (data.data.status == 1) {
          this.checkNameText = ''
        } else {
          let msg = data.data.msg
          this.checkNameText = msg.substring(msg.length - 4, msg.length)
        }
      }).catch(err => {
        this.$toast.center(err.msg)
      })
    },
    // 校验手机号
    validateBrandTel(tel) {
      this.$api.validateBrandTel(this.$route.query.catid, {
        tel: tel
      }).then(data => {
        if (data.data.status == 1) {
          this.checkPhone = ''
          this.checkPhoneFlag = true
          // 获取图片二维码并显示
          this.getRandom(10)
          this.codeShow = true
        } else {
          this.$emit('onErrShow', true)
          this.$emit('onMsgText', data.data.msg)
        }
      }).catch(err => {
        this.$toast.center(err.msg)
      })
    },
    // 获取图片验证码
    getImgCode() {
      this.imgCodeUrl = 'http://' + consts.domain + '/api/captchas.sms.png.php?rnd=' + this.random + '&auType=1'
    },
    // 获取指定位数随机数
    getRandom(num) {
      this.random = Math.floor((Math.random() + Math.floor(Math.random() * 9 + 1)) * Math.pow(10, num - 1))
      // 获取验证码
      this.getImgCode(this.random)
    },
    // 校验图片验证码
    checkImageCode() {
      if (!this.brandForm.tel) return this.checkPhone = '必填项'
      // 修改的话，不需要校验手机号， 直接获取图片
      if (this.oldTel && !this.codeShow) {
        this.getRandom(10)
        this.codeShow = true
        return
      }
      if (!this.checkPhoneFlag) {
        // 校验手机号名
        this.validateBrandTel(this.brandForm.tel)
        return
      }
      if (this.countDown <= 0) {
        if (!this.imgcode) {
          this.$toast.center('请填写图片验证码')
          return
        }
        // 图片验证码检验
        this.$api.checkImageCodeBrand({
          rnd: this.random,
          captcha: this.imgcode,
          auType: 1
        }).then(data => {
          if (data.data.status == 0) {
            this.$emit('onErrShow', true)
            this.$emit('onMsgText', data.data.msg)
            this.imgcode = ''
            this.getRandom(10)
          } else {
            // 获取短信码
            this.getSms()
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 获取短信码
    getSms() {
      this.$api.getSms(this.$route.query.catid, {
        action: 'm_sms_verif_post',
        auType: '1',
        tel: this.brandForm.tel,
        captcha: this.imgcode,
        rnd: this.random
      }).then(data => {
        if (data.data.status == 1) {
          this.time()
        } else {
          this.$emit('onErrShow', true)
          this.$emit('onMsgText', data.data.msg)
          this.imgcode = ''
          this.getRandom(10)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 验证码倒计时
    time() {
      clearInterval(this.codeTimer)
      this.countDown = 60
      this.codeTimer = setInterval(() => {
        this.countDown--
        if (this.countDown <= 0) {
          this.countDown = 0
          clearInterval(this.codeTimer)
        }
      }, 1000)
    },
    // 接受子组件传入参数
    showTemplate(e) {
      this.$emit('showTemplate', true, e)
    },
    inputAddress() {
      this.brandForm.address = addressRule(this.brandForm.address)
    },
    inputPhone() {
      this.brandForm.tel = numRule(this.brandForm.tel)
    }
  }
}
</script>
<style lang='scss' scoped>
.classify {
  background: #fff;
  padding: 0 0.3rem;
  .item {
    font-size: 0.28rem;
    line-height: 0.9rem;
    color: #666666;
    .star {
      width: 30%;
      display: inline-block;
      vertical-align: middle;
      &:after {
        content: "*";
        color: #fd4d4d;
        vertical-align: top;
      }
    }
    .middle-text {
      width: 68%;
      display: inline-block;
      vertical-align: middle;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.enterprise {
  width: 100%;
  background: #fff;
  margin: 0.2rem 0;
  padding: 0.3rem;
  h6 {
    font-size: 0.34rem;
    line-height: 0.34rem;
    margin-bottom: 0.2rem;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
  }
  .format-box {
    display: flex;
    justify-content: space-between;
    padding: 0.24rem 0;
    p {
      font-size: 0.24rem;
      color: rgba(189, 189, 189, 1);
      line-height: 0.34rem;
    }
    .see {
      cursor: pointer;
      .see-icon {
        display: inline-block;
        vertical-align: middle;
        margin-right: 0.14rem;
        width: 0.26rem;
        height: 0.26rem;
        background: url(../../../assets/img/eye-icon.png) center no-repeat;
        background-size: cover;
      }
      span {
        font-size: 0.24rem;
        font-weight: bold;
        color: rgba(115, 158, 251, 1);
        line-height: 0.3rem;
      }
    }
  }
}
.phone-box {
  width: 100%;
  background: #fff;
  margin: 0.2rem 0;
  padding: 0.3rem 0.3rem 0 0.3rem;
  .tap-text {
    font-size: 0.24rem;
    line-height: 0.6rem;
    font-weight: 500;
    color: rgba(115, 158, 251, 1);
    text-align: right;
    border-top: 1px solid #fff;
    margin-top: -1px;
  }
  .img-code-box {
    width: 100%;
    height: 0.68rem;
    margin-top: 0.1rem;
    border-left: 1px solid rgba(246, 246, 246, 1);
    text-align: right;
  }
}
.code-box {
  width: 100%;
  background: #fff;
  padding: 0.3rem;
  .right-text {
    cursor: pointer;
    color: rgba(115, 158, 251, 1) !important;
  }
}
</style>
